package cn.kooki.app.duobao.ui.Fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseFragment;
import cn.kooki.app.duobao.core.GlideCircleTransform;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.User.LoginResponse;
import cn.kooki.app.duobao.data.Bean.User.LoginType;
import cn.kooki.app.duobao.data.Bean.User.UserInfo;
import cn.kooki.app.duobao.data.Bean.base.BaseResponse;
import cn.kooki.app.duobao.data.bus.LoginChangeEvent;
import cn.kooki.app.duobao.data.bus.NewStateEvent;
import cn.kooki.app.duobao.data.bus.UserRefrshEvent;
import cn.kooki.app.duobao.ui.Activity.Comm.AuthVerifyActivity;
import cn.kooki.app.duobao.ui.Activity.Comm.WebViewActivity;
import cn.kooki.app.duobao.ui.Activity.Pay.ReChargeActivity;
import cn.kooki.app.duobao.ui.Activity.Share.MyShareActivity;
import cn.kooki.app.duobao.ui.Activity.User.BindActivity;
import cn.kooki.app.duobao.ui.Activity.User.ChangeRecordActivity;
import cn.kooki.app.duobao.ui.Activity.User.DuobaoBonusAcitivity;
import cn.kooki.app.duobao.ui.Activity.User.DuobaoRecordActivity;
import cn.kooki.app.duobao.ui.Activity.User.RegActivity;
import cn.kooki.app.duobao.ui.Activity.User.SettingActivity;
import cn.kooki.app.duobao.ui.Activity.User.UserPointsActivity;
import cn.kooki.app.duobao.ui.Activity.User.UserinfoActivity;
import cn.kooki.app.duobao.ui.Activity.User.WinRecordActivity;
import cn.kooki.app.duobao.ui.widget.PushWinDialogUtils;
import cn.kooki.app.duobao.util.DESUtils;
import cn.kooki.app.duobao.util.PhoneCheckUtils;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import cn.kooki.app.duobao.util.StringUtils;
import cn.kooki.app.duobao.util.TimeUtils;
import cn.kooki.app.duobao.util.manager.LoginManager;
import de.hdodenhof.circleimageview.CircleImageView;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;


/**
 * Created by xiong on 2015/11/25.
 */
@SuppressLint("ValidFragment")
public class UserFragment extends BaseFragment implements View.OnClickListener, LoginManager.LoginHandler {
    @Bind(R.id.notification_bell)
    ImageButton notificationBell;
    @Bind(R.id.user_avatar)
    ImageView userAvatar;
    @Bind(R.id.user_nickname)
    TextView userNickname;
    @Bind(R.id.user_grow_point)
    TextView userGrowPoint;
    @Bind(R.id.user_ic_master)
    ImageButton userIcMaster;
    @Bind(R.id.user_layout_1)
    RelativeLayout userLayout1;
    @Bind(R.id.user_my_coin)
    TextView userMyCoin;
    @Bind(R.id.user_recharge)
    Button userRecharge;
    @Bind(R.id.user_layout_2)
    RelativeLayout userLayout2;
    @Bind(R.id.user_good_on)
    ImageView userGoodOn;
    @Bind(R.id.user_good_on_text)
    TextView userGoodOnText;
    @Bind(R.id.user_revealed)
    ImageView userRevealed;
    @Bind(R.id.user_revealed_text)
    TextView userRevealedText;
    @Bind(R.id.user_follow)
    ImageView userFollow;
    @Bind(R.id.user_follow_text)
    TextView userFollowText;
    @Bind(R.id.user_layout_3)
    LinearLayout userLayout3;
    @Bind(R.id.user_ic_record)
    ImageView userIcRecord;
    @Bind(R.id.user_layout_duobaorecord)
    RelativeLayout userLayoutDuobaorecord;
    @Bind(R.id.user_layout_5)
    RelativeLayout userLayout5;
    @Bind(R.id.user_ic_coupon)
    ImageView userIcCoupon;
    @Bind(R.id.arrow_right_2)
    ImageView arrowRight2;
    @Bind(R.id.user_layout_coupon)
    RelativeLayout userLayoutCoupon;
    @Bind(R.id.user_ic_wish)
    ImageView userIcWish;
    @Bind(R.id.arrow_right_3)
    ImageView arrowRight3;
    @Bind(R.id.user_layout_wish)
    RelativeLayout userLayoutWish;
    @Bind(R.id.user_ic_task)
    ImageButton userIcTask;
    @Bind(R.id.user_layout_task)
    RelativeLayout userLayoutTask;
    @Bind(R.id.user_ic_level)
    ImageButton userIcLevel;
    @Bind(R.id.user_layout_level)
    RelativeLayout userLayoutLevel;
    @Bind(R.id.user_layout_10)
    RelativeLayout userLayout10;
    @Bind(R.id.user_ic_charge)
    ImageView userIcCharge;
    @Bind(R.id.user_layout_charge)
    RelativeLayout userLayoutCharge;
    @Bind(R.id.user_ic_win_record)
    ImageView userIcWinRecord;
    @Bind(R.id.user_layout_win_record)
    RelativeLayout userLayoutWinRecord;
    @Bind(R.id.user_ic_share)
    ImageView userIcShare;
    @Bind(R.id.user_layout_share)
    RelativeLayout userLayoutShare;
    @Bind(R.id.user_layout_13)
    RelativeLayout userLayout13;
    @Bind(R.id.user_ic_setting)
    ImageView userIcSetting;
    @Bind(R.id.user_layout_setting)
    RelativeLayout userLayoutSetting;
    @Bind(R.id.user_layout)
    ScrollView userLayout;
    @Bind(R.id.top_back)
    ImageButton topBack;
    @Bind(R.id.top_text_center)
    TextView topTextCenter;
    @Bind(R.id.top_refresh)
    ImageButton topRefresh;
    @Bind(R.id.top_cart)
    ImageButton topCart;
    @Bind(R.id.action_edit)
    TextView actionEdit;
    @Bind(R.id.toolbar)
    RelativeLayout toolbar;
    @Bind(R.id.registered_tips)
    TextView registeredTips;
    @Bind(R.id.registered_email)
    TextView registeredEmail;
    @Bind(R.id.registered_normal)
    TextView registeredNormal;
    @Bind(R.id.email_icon)
    ImageView emailIcon;
    @Bind(R.id.email)
    AutoCompleteTextView email;
    @Bind(R.id.email_wrapper)
    RelativeLayout emailWrapper;
    @Bind(R.id.pwd_icon)
    ImageView pwdIcon;
    @Bind(R.id.password)
    EditText password;
    @Bind(R.id.login_forget)
    TextView loginForget;
    @Bind(R.id.pass_wrapper)
    RelativeLayout passWrapper;
    @Bind(R.id.login)
    Button login;
    @Bind(R.id.login_reg)
    Button loginReg;
    @Bind(R.id.imageView)
    ImageView imageView;
    @Bind(R.id.more_auth_method)
    TextView moreAuthMethod;
    @Bind(R.id.auth_weixin_image)
    ImageButton authWeixinImage;
    @Bind(R.id.auth_weixin_text)
    TextView authWeixinText;
    @Bind(R.id.auth_qq_image)
    ImageButton authQqImage;
    @Bind(R.id.auth_qq_text)
    TextView authQqText;
    @Bind(R.id.auth_sina_image)
    ImageButton authSinaImage;
    @Bind(R.id.auth_sina_text)
    TextView authSinaText;
    @Bind(R.id.login_normal)
    LinearLayout loginNormal;
    @Bind(R.id.login_layout)
    LinearLayout loginLayout;
    @Bind(R.id.user_record_currt)
    RelativeLayout userRecordCurrt;
    @Bind(R.id.user_record_result)
    RelativeLayout userRecordResult;
    @Bind(R.id.duobao_record_points)
    RelativeLayout duobaoRecordPoints;
    @Bind(R.id.not_sign)
    ImageView notSign;
    @Bind(R.id.layout_points)
    RelativeLayout layoutPoints;
    private UserInfo userInfo;

    @Bind(R.id.layout_otherLogin_tips)
    FrameLayout layoutOtherLoginTips;

    private boolean islogin;
    private boolean isSign;
    private boolean isVisibleToUser;


    @Override
    public View setView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.user_fragment_content, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void afterView() {
//        mTencent = Tencent.createInstance(Constants.mAppid, context);

        islogin = SharePreferencesUtils.getBoolean(context, SharePreferencesUtils.ISLOGIN);

        refreshUser(islogin);
        loginReg.setOnClickListener(this);
        login.setOnClickListener(this);
        userLayoutSetting.setOnClickListener(this);
        userRecharge.setOnClickListener(this);
        userRecordCurrt.setOnClickListener(this);
        userRecordResult.setOnClickListener(this);
        userLayoutDuobaorecord.setOnClickListener(this);
        userLayoutCoupon.setOnClickListener(this);
        userAvatar.setOnClickListener(this);
        userLayoutCharge.setOnClickListener(this);
        userLayoutShare.setOnClickListener(this);
        userLayoutWinRecord.setOnClickListener(this);
        authSinaImage.setOnClickListener(this);
        authWeixinImage.setOnClickListener(this);
        authQqImage.setOnClickListener(this);
        loginForget.setOnClickListener(this);
        duobaoRecordPoints.setOnClickListener(this);
        notificationBell.setOnClickListener(this);
        hideNotsupport();

    }


    private void hideNotsupport() {
        int type = SharePreferencesUtils.getInt(context, LoginType.LOING);
        authWeixinImage.setVisibility(type == 1 ? View.VISIBLE : View.GONE);
        authWeixinText.setVisibility(type == 1 ? View.VISIBLE : View.GONE);
        authQqImage.setVisibility(type == 1 ? View.VISIBLE : View.GONE);
        authQqText.setVisibility(type == 1 ? View.VISIBLE : View.GONE);
        layoutOtherLoginTips.setVisibility(type == 1 ? View.VISIBLE : View.GONE);
    }

    private void refreshUser(boolean islogin) {
        if (islogin) {

            userInfo = SharePreferencesUtils.getUserinfo(context);
            if (!TextUtils.isEmpty(userInfo.getImg())) {
                Glide.with(context).load(userInfo.getImg()).transform(new GlideCircleTransform(context)).into(userAvatar);
            }
            userLayout.scrollTo(0, 0);
            String mymoney = "余额: " + StringUtils.nullSafeParseInt(userInfo.getMoney()) + " 抢宝币";
            SpannableString string = new SpannableString(mymoney);
            string.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.bonus_title)),
                    4, mymoney.length() - 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            userMyCoin.setText(string);
            userNickname.setText(userInfo.getUsername());
            userNickname.setVisibility(View.VISIBLE);
            userLayout.setVisibility(View.VISIBLE);
            loginLayout.setVisibility(View.GONE);
            topTextCenter.setVisibility(View.GONE);
        } else {
            userLayout.setVisibility(View.GONE);
            loginLayout.setVisibility(View.VISIBLE);
            topTextCenter.setText(R.string.login);
            topTextCenter.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshSign();
    }

    /**
     * 刷新签到状态
     */
    private void refreshSign() {

        isSign = SharePreferencesUtils.getBoolean(context, "isSign");
        long signtime = SharePreferencesUtils.getLong(context, "signtime");
        String time1 = TimeUtils.getTime(signtime, TimeUtils.DATE_FORMAT_DATE);
        String time2 = TimeUtils.getTime(signtime, TimeUtils.DATE_FORMAT_DATE);
        if (!StringUtils.isEquals(time1, time2)) {
            isSign = false;
            SharePreferencesUtils.putBoolean(context, "isSign", isSign);
            getuserinfo();
        }
        notSign.setVisibility(isSign ? View.INVISIBLE : View.VISIBLE);
    }


    public void onEventMainThread(LoginChangeEvent event) {
        refreshUser(event.islogin);
    }

    public void onEventMainThread(UserRefrshEvent event) {
        getuserinfo();
    }

    private void getuserinfo() {
        userInfo = SharePreferencesUtils.getUserinfo(context);
        MainFactory.getApiInstance().getuserinfo(userInfo.getUid(), new Callback<LoginResponse>() {
            @Override
            public void success(LoginResponse loginResponse, Response response) {
                if (loginResponse.getData() != null) {
                    SharePreferencesUtils.putUserinfo(context, loginResponse.getData());
                    islogin = SharePreferencesUtils.getBoolean(context, SharePreferencesUtils.ISLOGIN);
                    refreshUser(islogin);
                } else {
                    showToastMessage("获取用户数据失败,请重试或重新登录");
                }
            }

            @Override
            public void failure(RetrofitError error) {
                showToastMessage("获取用户数据失败,请重试或重新登录");
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onClick(View v) {
        if (v == loginReg) {
            intent(RegActivity.class);
        }
        if (v == login) {
            if (checkForm()) {
                dologin();
            }
        }
        if (v == authWeixinImage) {
            dologinWeixin();
        }
        if (v == loginForget) {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("type", WebViewActivity.FINDPASS_TYPE);
            hashMap.put("title", "找回密码");
            intent2(WebViewActivity.class, hashMap);
        }

        if (v == authSinaImage) {
            dologinSina();
        }
        if (v == authQqImage) {
            dologinQQ();
        }

        if (v == userLayoutCharge) {
            intent(ChangeRecordActivity.class);
        }
        if (v == userLayoutSetting) {
            intent(SettingActivity.class);
        }
        if (v == userRecharge) {
            if (PhoneCheckUtils.checkphone(context)) {
                intent(ReChargeActivity.class);
            } else {
                intent(BindActivity.class);
            }
        }
        if (v == userLayoutDuobaorecord) {
            intent(DuobaoRecordActivity.class);
        }
        if (v == userRecordCurrt) {
            intent(DuobaoRecordActivity.class, "type", 1);
        }
        if (v == userRecordResult) {
            intent(DuobaoRecordActivity.class, "type", 2);
        }
        if (v == userLayoutCoupon) {
            intent(DuobaoBonusAcitivity.class);
        }
        if (v == userAvatar) {
            intent(UserinfoActivity.class);
        }
        if (v == userLayoutShare) {
            intent(MyShareActivity.class);
        }
        if (v == userLayoutWinRecord) {
            intent(WinRecordActivity.class);
        }
        if (v == duobaoRecordPoints) {
            intent(UserPointsActivity.class);
        }
        if (v == notificationBell) {
            HashMap<String, Object> params = new HashMap<>();
            params.put("type", WebViewActivity.NOTICE_TYPE);
            intent2(WebViewActivity.class, params);
        }
    }


    private void dologinQQ() {
        doLoginOther(1);
    }

    private void dologinWeixin() {
        doLoginOther(0);
    }

    public void doLoginOther(final int type) {
        Intent intent = new Intent(context, AuthVerifyActivity.class);
        intent.putExtra("type", type);
        startActivity(intent);
    }

    private void dologinSina() {
        doLoginOther(2);
    }

    private void dologin() {
        showLoading(getString(R.string.login_loading));
        String md5 = DESUtils.MD5(password.getText().toString());
        LoginManager manager = new LoginManager();
        manager.doLogin(context, email.getText().toString(), md5, this);
    }

    private boolean checkForm() {
        hideSoftKeyBoard();
        if (TextUtils.isEmpty(email.getText().toString())) {
            showToastMessage(R.string.moblie_is_empty);
            return false;
        }
        if (TextUtils.isEmpty(password.getText().toString()) || password.getText().length() < 6) {
            return false;
        }

        return true;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        if (isVisibleToUser) {
            boolean islogin = SharePreferencesUtils.getBoolean(context, SharePreferencesUtils.ISLOGIN);
            if (islogin) {
                UserInfo userinfo = SharePreferencesUtils.getUserinfo(context);
                boolean isNew = SharePreferencesUtils.getBoolean(context, userinfo.getUid(), "isNew", false);
                if (isNew) {
                    showNew();
                }
            }
        }
    }

    public void onEventMainThread(NewStateEvent event) {
        boolean islogin = SharePreferencesUtils.getBoolean(context, SharePreferencesUtils.ISLOGIN);
        if (islogin && event.isNew) {
            SharePreferencesUtils.putBoolean(context, event.uid, "isNew", true);
            if (isVisibleToUser) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showNew();
                    }
                }, 200);
            }
        }else {
            SharePreferencesUtils.putBoolean(context, event.uid, "isNew", false);
        }
    }

    public void showNew() {
        PushWinDialogUtils.showFristDilaog(context, false);
    }


    @Override
    public void onLoginStart() {
        showLoading("正在登陆");
    }

    @Override
    public void onLoginComplete() {
        refreshUser(true);
        email.setText("");
        password.setText("");
        dismissLoading();
    }

    @Override
    public void onLoginFair(String msg) {
        dismissLoading();
        showToastErrorMessage(msg);
    }

    @Override
    public void onOtherLoginComplete() {
        refreshUser(true);
    }


}
